import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'

import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
import cellData from './modules/cellData'

Vue.use(Vuex)

// 扩展 file n+ modules

/**
 * (Vuex不会保存起来,刷新之后就回到了初始状态)
 * 扩展 Vuex 与 localStorage 
 * 在 vuex 里数据改变的时候把数据拷贝一份保存到 localStorage 里面
 * 刷新之后，如果 localStorage 里有保存的数据，取出来再替换 store 里的 state
 */

// https://webpack.js.org/guides/dependency-management/#requirecontext
const getModules = (controllers, moduleNameSuffix = '') => {
  const modules = {}
  if (controllers) {
    controllers.keys().forEach(fileName => {
      let moduleName = fileName
      const index = fileName.lastIndexOf('/')
      if (index >= 0) {
        moduleName = fileName.substring(index + 1)
      }
      moduleName = moduleName.replace(/\.js$/, '')

      let controllerConfig = controllers(fileName)
      controllerConfig = controllerConfig.default || controllerConfig
      modules[moduleName + moduleNameSuffix] = controllerConfig
    })
  }
  return modules
}
let toModules = getModules(require.context('./toModules', false, /\.js$/))
// toModules中filename != modules中filename 
// toMfileName == mFileName -> replace onlyOne
const store = new Vuex.Store({
  modules: {
    ...toModules,
    app,
    settings,
    user,
    cellData
  },
  getters
})

export default store
